package com.ruoyi.framework.web.service.custom;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysMiniUser;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysMiniUserService;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


/**
 * 小程序用户通过密码登录
 * 2023-4-7
 */
@Service
public class MiniUserPasswordDetailService implements CustomUserDetailService {

    private static final Logger log = LoggerFactory.getLogger(AdminUserDetailService.class);

    private  final String TYPE= Constants.USER_TYPE_MINI_PASSWORD;

    @Autowired
    private ISysMiniUserService miniUserService;


    @Override
    public Boolean supports(String type) {
        return TYPE.equals(type);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysMiniUser sysMiniUser = miniUserService.selectSysMiniUserByJobNumber(username);
        if (StringUtils.isNull(sysMiniUser))
        {
            log.info("用户：{}不存在.", username);
            throw new ServiceException("用户：" + username + " 不存在");
        }
        return createLoginUser(sysMiniUser);
    }

    public UserDetails createLoginUser(SysMiniUser sysMiniUser) {
        SysUser sysUser = new SysUser();
        LoginUser loginUser = new  LoginUser(sysUser.getUserId(),sysUser.getDeptId(),sysUser,sysMiniUser,null);
        return loginUser;
    }
}
